package cn.myframe.utils.ssh;

import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

@Component
public class SSHUtils {
	public static Map<String,SSHData> sshMap = new HashMap<String,SSHData>();
	/**
	 * sshMap数据超时时间
	 */
	public static Long OUT_TIME = 180_000L;
	
	public static ChannelShell getShellChannel(String user, String host, Integer port ,String password, String id){
		ChannelShell channel = null;
		try {
	        JSch jsch = new JSch();
	        jsch.getSession(user, host, port);
	        Session session = jsch.getSession(user, host, port);
	        //log.info("Session created.");
	        session.setPassword(password);
	        Properties sshConfig = new Properties();
	        sshConfig.put("StrictHostKeyChecking", "no");
	        session.setConfig(sshConfig);
	        session.connect();
	        channel = (ChannelShell) session.openChannel("shell");
	        channel.setEnv("LANG", "zh_CN.UTF8");
	        channel.setAgentForwarding(false);
	        channel.connect();
	        channel.setPtySize(500, 500, 1000, 1000);
	        SSHData sshData = new SSHData(session, channel);
        	SSHUtils.sshMap.put(id,sshData);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
       return channel;
   }
	
	public static SSHData getSSHData(String user, String host, Integer port ,String password){
		ChannelShell channel = null;
		SSHData sshData = null;
		try {
			JSch jsch=new JSch();
	        Session session = jsch.getSession(user,host,port);
	        session.setPassword(password);
	        session.setUserInfo(new MyUserInfo());
	        session.connect();
	        channel = (ChannelShell) session.openChannel("shell");
	        channel.setEnv("LANG", "zh_CN.UTF8");
	        channel.setAgentForwarding(false);
	        channel.connect();
	        channel.setPtySize(500, 500, 1000, 1000);
	        sshData = new SSHData(session, channel);
        	
		} catch (Exception e) {
			return null;
		}
       return sshData;
   }
	
	private static class MyUserInfo implements UserInfo{
	    @Override
	    public String getPassphrase() {
	        System.out.println("getPassphrase");
	        return null;
	    }
	    @Override
	    public String getPassword() {
	        System.out.println("getPassword");
	        return null;
	    }
	    @Override
	    public boolean promptPassword(String s) {
	        System.out.println("promptPassword:"+s);
	        return false;
	    }
	    @Override
	    public boolean promptPassphrase(String s) {
	        System.out.println("promptPassphrase:"+s);
	        return false;
	    }
	    @Override
	    public boolean promptYesNo(String s) {
	        System.out.println("promptYesNo:"+s);
	        return true;//notice here!
	    }
	    @Override
	    public void showMessage(String s) {
	        System.out.println("showMessage:"+s);
	    }
	}
	
	@PostConstruct
	public void init(){
		ExecutorService executorService=Executors.newFixedThreadPool(1);
		Runnable runnable=new Runnable() {
			@Override
			public void run() {
				byte[] tmp=new byte[1024];
				while(true){
					try{
						//校验sshMap的超时时间
						Set<Entry<String, SSHData>> entries = sshMap.entrySet();
						Set<String> remSet =  new HashSet<>();
				    	for(Entry<String, SSHData> entry : entries){
				    		SSHData sshData = entry.getValue();
				    		if(sshData.checkOutTime(OUT_TIME)){
				    			sshData.destory();
				    			remSet.add(entry.getKey());
				    		}
				    	}
				    	for(String key : remSet){
				    		sshMap.remove(key);
				    	}
						Set<String> set = sshMap.keySet();
					    if(set != null ){
					    	for(String key : set){
					    		SSHData  sshData = sshMap.get(key);
					    		InputStream in = sshData.getInputStream();
					    		/*BufferedReader reader = new BufferedReader(  
					                     new InputStreamReader(in)); */
					    		while(in.available()>0){
					    			sshData.freshTime();
				                    int i=in.read(tmp, 0, 1024);
				                    if(i<0)break;
				                    System.out.print(new String(tmp, 0, i));
				                    SSHQueue.getInstance().push(new SSHMessage(String.valueOf(key),new String(tmp, 0, i)));
					    		}
					    	}
					    }
					}catch(Exception e){
						e.printStackTrace();
					}
					try{Thread.sleep(1000);}catch(Exception ee){}
				}
			}
		};
		executorService.submit(runnable);
	}
  
}

